import plugin from '../../../lib/plugins/plugin.js'
import fs from 'node:fs'
import { Config } from '../components/index.js'
export class Xy_Chuochuo extends plugin {
  constructor () {
    super({
      name: '小月戳一戳',
      dsc: '小月戳一戳',
      event: 'notice'
    })
  }

  async accept (e) {
    let data = JSON.parse(await redis.get('xioayue:switchBot:data')) ?? {}
    if (data[e.group_id] && !data[e.group_id]?.switch && !Config.masterQQ.includes(e.user_id)) {
      return true
    }
    let config = Config.xyss
    if (!config.chuochuo) return
    if (!e.sub_type == 'poke') return
    if (this.cd || e.target_id != Bot.uin) return
    let chuo = Config.xycc
    let wenan = chuo.wenan
    if (wenan.length) e.reply(wenan[Math.floor(Math.random() * wenan.length)])
    if (config.chuoapi) {
      try {
        let num = Math.ceil(Math.random() * 4)
        if (config.chuorecord) {
          e.reply(num < 3 ? segment.record('https://imagesapi.sesepic.top/ysvoice') : segment.image('https://yxy-api.yize.site/api/chuo/'))
        } else {
          e.reply(segment.image('https://yxy-api.yize.site/api/chuo/'))
        }
      } catch (err) {
        logger.error(err)
        e.reply('接口失效')
      }
    } else {
      await initFile()
      let chuopath = process.cwd() + '/plugins/xiaoyue-plugin/resources/xychuo/image/'
      let chuorecord = process.cwd() + '/plugins/xiaoyue-plugin/resources/xychuo/record/'
      let chuoFile = fs.readdirSync(chuopath)
      let chuored = fs.readdirSync(chuorecord)
      let num = Math.ceil(Math.random() * 2)
      if (!chuoFile.length && !chuored.length) return
      if ((config.chuorecord && chuored.length && num == 1) || (num == 2 && !chuoFile.length && config.chuorecord && chuored.length)) {
        let recordnum = Math.round(Math.random() * (chuored.length - 1))
        e.reply(segment.record(chuorecord + chuored[recordnum]))
        return
      }

      if (!chuoFile.length) return
      let imagenum = Math.round(Math.random() * (chuoFile.length - 1))
      e.reply(segment.image(chuopath + chuoFile[imagenum]))
    }
  }
}

async function initFile () {
  let chuopath = process.cwd() + '/plugins/xiaoyue-plugin/resources/xychuo/'
  if (!fs.existsSync(chuopath)) fs.mkdirSync(chuopath)
  if (!fs.existsSync(chuopath + '/image/')) fs.mkdirSync(chuopath + '/image/')
  if (!fs.existsSync(chuopath + '/record/')) fs.mkdirSync(chuopath + '/record/')
}
